import Taro, { Component } from '@tarojs/taro'
import { View, Icon, Input } from '@tarojs/components'
import './search.scss'
import ProductItem from "../../components/ProductItem/ProductItem";
import {guaranteeModes, style } from '../../config/index'
import request from '../utils/request'
import {getBankImgUrl} from '../../config/getImgs'

export default class Search extends Component {

  config = {
    navigationBarTitleText: '搜索'
  }

  constructor(props) {
    super(props);
    this.state = {
      searchValue: '',
      products: [],
      showHistory: true,
      searchHistory: []
    }
  }

  componentDidMount() {
    let searchHistory = Taro.getStorageSync('searchHistory');
    if(searchHistory === '') searchHistory = [];
    this.setState({
      searchHistory
    })
  }

  judgeRepeat(search_value) {
    let {searchHistory} = this.state;
    if(searchHistory.indexOf(search_value) === -1) return true;
    return false;
  }

  search(keywords) {
    if (keywords.replace(/(^s*)|(s*$)/g, "").length ==0) return;  //输入的内容为空
    let data = {
      instName: '',
      productName: keywords
    }
    request.get('/loudi-poc/product/list', data).then((res) => {
      let products1 = res.data.data;
      let data2 = {
        instName: keywords,
        productName: ''
      }
      request.get('/loudi-poc/product/list', data2).then((res2) => {
        let products2 = res2.data.data;
        let products = products1.length > 0 ? products1 : products2;
        this.setState({
          products,
          showHistory: false
        })
      })
    })

    let {searchHistory} = this.state;
    if(this.judgeRepeat(keywords)) {  //不在历史记录中则添加至历史记录
      searchHistory.push(keywords);
      this.setState({
        searchHistory
      })
      Taro.setStorageSync('searchHistory', searchHistory)
    }
  }

  cancel() {
    Taro.navigateBack({
      delta: 1
    })
  }

  setValue(value) {
    this.search(value);
    this.setState({searchValue: value});
  }

  removeHistory(index) {
    let {searchHistory} = this.state;
    searchHistory.splice(index, 1);
    this.setState({
      searchHistory
    })
    Taro.setStorageSync('searchHistory', searchHistory)
  }

  removeAll() {
    let searchHistory = [];
    this.setState({
      searchHistory
    })
    Taro.setStorageSync('searchHistory', searchHistory)
  }

  render () {
    let products = this.state.products;
    let searchHistory = this.state.searchHistory;
    return (
      <View className='search'>
        <View className='search_row'>
          <View className='search_input'>
            <Icon size='14' type='search'></Icon>
            <Input focus placeholder='请输入产品名称/机构名称' onConfirm={(event) => {this.search(event.detail.value)}} value={this.state.searchValue}></Input>
          </View>
          <View className='search_cancel' onClick={this.cancel}>取消</View>
        </View>
        <View className='search_hostory' style={this.state.showHistory ? style.show : style.hide}>
          <View className='his_title'>
            <View className='h1'>历史搜索</View>
            <View className='h2' onClick={this.removeAll}>清空记录</View>
          </View>
          <View className='his_items'>
            {
              searchHistory.map((item, index) => (
                <View className='his_item' key={index}>
                  <View className='his_item_name' onClick={() => {this.setValue(item)}}>{item}</View>
                  <View className='his_item_del' onClick={() => {this.removeHistory(index)}}>×</View>
                </View>
              ))
            }
          </View>
        </View>
        {
          products.map((item) => (
            <ProductItem
              key={item.id}
              url={'/pages/product/details?id='+item.id}
              openType='navigate'
              src={getBankImgUrl(item.logoCode)}
              name={item.productName}
              productType={guaranteeModes[item.guaranteeMode]}
              rate={item.loanRateLower+'%~'+item.loanRateUpper+'%'}
              time={item.loanTermLower+'~'+item.loanTermUpper+'个月'}
              rateType='参考利率'
            />
          ))
        }
      </View> 
    )
  }
}
